package LinkList;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: LinkList
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-23  08:35
 * @Description: TODO
 * @Version: 1.0
 */
public class 合并两个有序链表21 {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode head1 = list1;
        ListNode head2 = list2;

        ListNode dumpy = new ListNode(-1);
        ListNode curr = dumpy;
        // 判断的两个指针都没有到末尾 相当于是三指针的比较
        while (head1 != null && head2 != null) {
            if (head1.val > head2.val) {
                curr.next = head2;
                head2 = head2.next;
            } else {
                curr.next = head1;
                head1 = head1.next;
            }
            curr = curr.next;
        }
        if (head1 == null) {
            curr.next = head2;
        }
        if (head2 == null) {
            curr.next = head1;
        }
        return dumpy.next;
    }
}
